import settings from "../utils/settings";
import { stripRank , getSBProfile, RemoveEmoji, drawBoxAtEntity, partylist, getskulltextures, sendEssentialNotifications, getPlayerPos, getEntityHP, getItemSBID } from "../utils/utils";
import { location } from "../utils/getLocation";
import { Vec3 } from "../utils/vec3";


function dungeonWelcomeTitle() {
    if(settings.dungeonwelcometitle && location.inDungeon) {
        Client.showTitle(location.island,location.location,0,1,0); //不知道为什么进入世界后的第一个Title显示不出来
        switch (location.location.split(' ')[2][1]) {
            case 'E':
                Client.showTitle("§4§lThe Catacombs Entrance" , "" , 5 , 100 , 5);
                break;
            case 'F':
                Client.showTitle("§4§lThe Catacombs Floor " + location.location.split(' ')[2][2] , "" , 5 , 100 , 5);
                break;
            case 'M':
                Client.showTitle("§4§lThe Catacombs Floor " + location.location.split(' ')[2][2] , "§4§lMaster Mode" , 5 , 100 , 5);
                break;
        }
    }
}

function kuudraWelcomeTitle() {
    if(settings.kuudrawelcometitle && location.inKuudra) {   
        Client.showTitle(location.island,location.location,0,1,0); //不知道为什么进入世界后的第一个Title显示不出来
        switch (location.location.split(' ')[2]) {
            case "(T1)":
                Client.showTitle("§b§lKuudra" , "§e§lBasic Tier (T1)" , 5 , 100 , 5);
                break;
            case "(T2)":
                Client.showTitle("§b§lKuudra" , "§e§lHot Tier (T2)" , 5 , 100 , 5);
                break;
            case "(T3)":
                Client.showTitle("§b§lKuudra" , "§e§lBurning Tier (T3)" , 5 , 100 , 5);
                break;
            case "(T4)":
                Client.showTitle("§b§lKuudra" , "§e§lFiery Tier (T4)" , 5 , 100 , 5);
                break;
            case "(T5)":
                Client.showTitle("§b§lKuudra" , "§e§lInfernal Tier (T5)" , 5 , 100 , 5);
                break;
        }
    }
}

//blood ready
register("chat", () => {
    if(!settings.bloodready) return;
    if(!location.inDungeon) return;
    Client.showTitle(`§4Blood Ready`, "", 2, 60, 2);
    if(!InstanceStats.solo) ChatLib.command(`pc Blood room ready!`); else ChatLib.simulateChat(`§6[BZA] §4Blood room ready!`);
}).setChatCriteria("[BOSS] The Watcher: That will be enough for now.");

//Dupe Archer Check And Dungeon Ready Check
function DupeArcherAndReadyCheck() {
    if(settings.dupearcher && location.inDungeon) {   //dupe archer!!!
        setTimeout(() => {
            const archers = Scoreboard.getLines().filter(e => e.toString().includes("[A]")).length;
            if (archers > 1) {
                if(settings.dupearcher == 1.0 || settings.dupearcher == 3.0) ChatLib.chat("§4§l" + settings.dupearchertext)
                if(settings.dupearcher == 2.0 || settings.dupearcher == 3.0 || settings.dupearcher == 4.0) Client.showTitle("§4§lDupe Archer!!!","",0,40,5)
                if(settings.dupearcher == 4.0) ChatLib.command(`pc ` + settings.dupearchertext)
            }
        }, 2500);
    }
    if(settings.dungeonready && location.inDungeon){   //xxx not ready
        let notreadyplayer = "";
        setTimeout(() => {
            Scoreboard.getLines().filter(e => e.toString().length > 2 && e.toString()[2] == "[" && e.toString()[1] == "c").forEach(e => {
               notreadyplayer += ChatLib.removeFormatting(RemoveEmoji(e.toString().split(" ")[1]) + " ");
            })
            if(notreadyplayer != ""){
                ChatLib.command("pc " + settings.dungeonreadymessage.replace("%player%",notreadyplayer));
            }
        }, settings.dungeonready * 1000);
    }
}

//box star and fels
register("renderWorld", (ticks) => {
    if(settings.boxstarmobs && location.inDungeon) {
        World.getAllEntitiesOfType(net.minecraft.entity.item.EntityArmorStand).filter(e => e.getName().removeFormatting().startsWith('✯') && e.getName().removeFormatting().endsWith('❤')).forEach(e => {
            if(e.getName().includes("Fels")) {
                drawBoxAtEntity(e,settings.boxstarfelsColor.getRed()/255,settings.boxstarfelsColor.getGreen()/255,settings.boxstarfelsColor.getBlue()/255,settings.boxstarfelsColor.getAlpha()/255,1,1,-3,ticks,4);
            } else {
                drawBoxAtEntity(e,settings.boxstarmobsColor.getRed()/255,settings.boxstarmobsColor.getGreen()/255,settings.boxstarmobsColor.getBlue()/255,settings.boxstarmobsColor.getAlpha()/255,1,1,-2,ticks,4);
            }
        })
    }
    if(settings.boxfels && location.inDungeon) {
        World.getAllEntitiesOfType(net.minecraft.entity.item.EntityArmorStand).filter(e => !e.getName().removeFormatting().startsWith('✯') && e.getName().includes("Fels") && e.getName().removeFormatting().endsWith('❤')).forEach(e => {
            drawBoxAtEntity(e,settings.boxnostarfelsColor.getRed()/255,settings.boxnostarfelsColor.getGreen()/255,settings.boxnostarfelsColor.getBlue()/255,settings.boxnostarfelsColor.getAlpha()/255,1,1,-3,ticks,4)
        })
    }
    if(settings.boxstarmobs && location.inDungeon) {
        World.getAllEntitiesOfType(net.minecraft.client.entity.EntityOtherPlayerMP).filter(e => e.getName() == "Shadow Assassin").forEach(e => {
            drawBoxAtEntity(e,settings.boxnostarfelsColor.getRed()/255,settings.boxnostarfelsColor.getGreen()/255,settings.boxnostarfelsColor.getBlue()/255,settings.boxnostarfelsColor.getAlpha()/255,1,1,2,ticks,6)
        })
    }
})

//除去地牢内sa的隐身
register("step", () => {
    if(!settings.boxstarmobs || !location.inDungeon) return;
    World.getAllEntitiesOfType(net.minecraft.client.entity.EntityOtherPlayerMP).filter(e => e.getName() == "Shadow Assassin").forEach(e => {
        e.getEntity().func_82142_c(false);  //setInvisible
    })
}).setDelay(1)

//标记地牢内的凋零钥匙和血房钥匙
let key = [];
register("tick" , () => {
    if(!location.inDungeon || !settings.WitherKey) return;
    key = World.getAllEntitiesOfType(net.minecraft.entity.item.EntityArmorStand).filter( e =>
        e && e.getEntity().func_71124_b(4) &&
        getskulltextures(e.getEntity().func_71124_b(4)) === "ewogICJ0aW1lc3RhbXAiIDogMTYwMzYxMDQ0MzU4MywKICAicHJvZmlsZUlkIiA6ICIzM2ViZDMyYmIzMzk0YWQ5YWM2NzBjOTZjNTQ5YmE3ZSIsCiAgInByb2ZpbGVOYW1lIiA6ICJEYW5ub0JhbmFubm9YRCIsCiAgInNpZ25hdHVyZVJlcXVpcmVkIiA6IHRydWUsCiAgInRleHR1cmVzIiA6IHsKICAgICJTS0lOIiA6IHsKICAgICAgInVybCIgOiAiaHR0cDovL3RleHR1cmVzLm1pbmVjcmFmdC5uZXQvdGV4dHVyZS9lNDllYzdkODJiMTQxNWFjYWUyMDU5Zjc4Y2QxZDE3NTRiOWRlOWIxOGNhNTlmNjA5MDI0YzRhZjg0M2Q0ZDI0IgogICAgfQogIH0KfQ==" ||
        getskulltextures(e.getEntity().func_71124_b(4)) === "ewogICJ0aW1lc3RhbXAiIDogMTcwODY4ODA2MjE4OCwKICAicHJvZmlsZUlkIiA6ICIzNzRhZGZlMjkyOWI0ZDBiODJmYmVjNTg2ZTI5ODk4YyIsCiAgInByb2ZpbGVOYW1lIiA6ICJfR2xvenpfIiwKICAic2lnbmF0dXJlUmVxdWlyZWQiIDogdHJ1ZSwKICAidGV4dHVyZXMiIDogewogICAgIlNLSU4iIDogewogICAgICAidXJsIiA6ICJodHRwOi8vdGV4dHVyZXMubWluZWNyYWZ0Lm5ldC90ZXh0dXJlLzIwZGU1ZTg5NzQ5NDAzNzU5MzRkMzJmNzFjOTFhZDJkNTcyOGQzOGU1MTY0N2RjYzhmMzkyMDZjMDk5YTU0YzIiCiAgICB9CiAgfQp9"
    )
})
register("renderWorld" , () => {
    if(!location.inDungeon || !settings.WitherKey || key.length == 0) return;
    key.forEach(e => {
        try {
            Tessellator.drawString("§a§lKEY",e.getRenderX(),e.getRenderY() + 2.1,e.getRenderZ(),0,false,0.08,false)
        } catch (error) {
            ChatLib.chat(error)
        }
    })
})

//地牢内禁用还债
register("playerInteract", (action,pos,event) => {
    if(settings.NoAlignedInDungeon && location.inDungeon && Player.getHeldItem() && Player.getHeldItem().getName().includes("Gyrokinetic Wand")) cancel(event);
})

//地牢每日计数
function DungeonComp() {
    let DungeonDaily = {}
    const ProfileName = location.SBProfile;
    DungeonDaily[ProfileName] = {runs:0,timestamp:0}
    if(FileLib.exists("./config/ChatTriggers/modules/BabyzombieAddons/config/DungeonDaily.json")) {
        DungeonDaily = Object.assign(DungeonDaily,JSON.parse(FileLib.read("./config/ChatTriggers/modules/BabyzombieAddons/config/DungeonDaily.json")));
    }
    let date = new Date(Date.now());
    let days = date.getUTCFullYear() * 10000 + ( date.getUTCMonth() + 1 ) * 100 + date.getUTCDate();
    if(DungeonDaily[ProfileName].timestamp == days) {
        DungeonDaily[ProfileName].runs ++;
    } else {
        DungeonDaily[ProfileName].runs = 1;
        DungeonDaily[ProfileName].timestamp = days;
    }
    FileLib.write("./config/ChatTriggers/modules/BabyzombieAddons/config/DungeonDaily.json",JSON.stringify(DungeonDaily,null,4),true);
    switch (settings.DungeonDaily) {
        case 0:
            return;
        case 1:
            if(DungeonDaily[ProfileName].runs > 5) return;
    }
    setTimeout(() => { ChatLib.chat(new Message("§6§l[BZA] §b地牢每日场数:" + (DungeonDaily[ProfileName].runs > 5 ? " §e" : " §a") + DungeonDaily[ProfileName].runs + "/5").setRecursive(true)); }, 100);
}


//在地牢4层隐藏看台上的观众
register("renderEntity", (entity,pos,tick,event) => {
    if(!location.inDungeon || !location.location.includes("4") || settings.HideCrowdInF4 == 0 || !getPlayerPos().isIn(new Vec3i(-40,0,-40),new Vec3i(50,255,50))) return;
    switch (entity.getClassName()) {
        case "EntityOtherPlayerMP":
            if(!entity.getName().includes(' ') || entity.getName() == "Decoy " || entity.getName() == "Spirit Bear") break;
        case "EntityZombie":
        case "EntitySkeleton":
            if(settings.HideCrowdInF4 == 1) cancel(event); else entity.getEntity().func_70106_y();  //setDead();
            break;
    }
})

//取消storm死后的雷声
const cancelLighting = register("soundPlay", (pos,name,vol,pit,cate,event) => {
    if(name === "ambient.weather.thunder") cancel(event); 
}).unregister();
register("chat", () => {
    if(!settings.MuteStorm || !location.inSkyblock || !location.inDungeon) return;
    cancelLighting.register();
    setTimeout(() => { cancelLighting.unregister(); }, 22000);
}).setCriteria("[BOSS] Storm: I should have known that I stood no chance.")

//自动关闭箱子页面
let closeChestGui = 0;
register("playerInteract",(action,pos,event) => {
    if(!settings.AutoCloseChestGui || !location.inSkyblock || !location.inDungeon) return;
    if(action.toString() != "RIGHT_CLICK_BLOCK") return;
    const block = World.getBlockAt(pos.x,pos.y,pos.z);
    if(block.getType().getRegistryName() != "minecraft:chest") return;
    closeChestGui = Date.now();
})
register("guiRender", () => {
    if(!settings.AutoCloseChestGui || !location.inSkyblock || !location.inDungeon) return;
    if(closeChestGui == 0) return;
    if(Date.now() - closeChestGui > 500) {closeChestGui = 0;return;}
    Client.currentGui.close();
})

//清除凋零套的小凋零
register("renderEntity", (entity,pos,tick,event) => {
    if(!location.inSkyblock || [2,4,6,7].indexOf(settings.clearEntity) == -1) return;
    if(Player.armor.getHelmet() == null || !getItemSBID(Player.armor.getHelmet()).includes("WITHER_HELMET")) return;
    if(entity.getClassName() != "EntityWither" || entity.distanceTo(Player.getPlayer()) > 3 ) return;
    if(entity.getEntity().func_82212_n() != 800 || getEntityHP(entity).hp != 300 || getEntityHP(entity).maxhp != 300 || entity.getPitch() !== 0) return;
    entity.getEntity().func_70106_y();
})


//地牢和kuudra 自动重开
/**
 * @param {String} text 在party chat发送的消息
 * @param {number} time 多久后输入指令 instancerequeue
 * @returns 
 */
function InstanceRequeue(text,time) {
    if(!location.inSkyblock || !(InstanceStats.leader || InstanceStats.solo) || InstanceStats.AutoJoinCancel) return;
    if(InstanceStats.solo) ChatLib.chat("§6§l[BZA] §a将在" + time + "秒后自动重开");
    else if(text) ChatLib.command('pc ' + text.replace('%delay%',time));
    if(time != 0) {
        setTimeout(() => {
            if(!location.inDungeon && !location.inKuudra) return;
            if(InstanceStats.AutoJoinCancel) return;
            ChatLib.command("instancerequeue");
        }, time * 1000);
    } else ChatLib.command("instancerequeue");
}

export let InstanceStats = {
    started : false,
    end : false,
    AutoJoinCancel : false,
    leader : false,
    solo : false,
    CancelAutoJoin(command = false) {
        if (!(this.solo || this.leader) || this.AutoJoinCancel) return;
        this.AutoJoinCancel = true;
        if (command) {
            ChatLib.chat("§6§l[BZA] §4已取消本局自动重开")
        } else {
            if(!((settings.AutoRequeueDungeon && location.inDungeon) || (settings.AutoRequeueKuudra && location.inKuudra))) return;
            if(settings.AutoRequeueCancel && !this.solo){
                setTimeout(() => {
                    ChatLib.command(`pc ` + settings.AutoRequeueCancel)
                }, 300);
            }else{
                ChatLib.chat("§6§l[BZA] §4已取消本局自动重开")
            }
        }
    }
}

register("worldLoad", () => {
    InstanceStats.started = false;
    InstanceStats.end = false;
    InstanceStats.AutoJoinCancel = false;
    InstanceStats.leader = false;
    InstanceStats.solo = false;
    EnterInstance.register();
    setTimeout(() => { EnterInstance.unregister(); }, 30000);
})

//进入地牢或kuudra并且服务器信息加载完成时
const EnterInstance = register("tick", () => {
    if(!location.island || !location.location || location.location == "None") return;
    try {
        if(!location.inDungeon && !location.inKuudra) {
            EnterInstance.unregister();
            return;
        }
        partylist.get(party => partyCheck(party));
        if(location.inDungeon) { DupeArcherAndReadyCheck(); dungeonWelcomeTitle();}
        else if(location.inKuudra) kuudraWelcomeTitle();
    } catch (error) {}
    EnterInstance.unregister();
});

function partyCheck(party) {
    if(Object.keys(party).length <= 1) {
        InstanceStats.solo = true;
        InstanceStats.end = false;
        return;
    }
    InstanceStats.leader = party[Player.getUUID()] === "LEADER";
    if(settings.InstanceWarp && InstanceStats.leader) setTimeout(() => {
        const players = Number(TabList.getNames()[0].removeFormatting().replace(/[^0-9]/ig,""));
        if(Object.keys(party).length > players) {
            ChatLib.command("party warp");
            World.playSound("mob.wither.death",1,1);   // ↓ 刷个两次,免得有时候显示不出来 ↓
            Client.showTitle("§e" + players + " §7/ §b" + (Object.keys(party).length),"§c房间内人数小于队伍人数,正在尝试warp",0,80,20);
            Client.showTitle("§e" + players + " §7/ §b" + (Object.keys(party).length),"§c房间内人数小于队伍人数,正在尝试warp",0,80,20);
            sendEssentialNotifications("§6BabyzombieAddons","§c您的小队中有 §b" + (Object.keys(party).length) + " §c名玩家\n§c但是当前房间只有 §e" + players + " §c名玩家\n§c因此module进行了一次自动 /p warp\n§c请注意您的队友是否成功进入了房间", 10);
        }
    }, 1000);
}

register("chat", (message) => {
    if(!location.inSkyblock) return;
    if(!location.inDungeon && !location.inKuudra) return;
    if(message == "Starting in 1 second." ) {
        InstanceStats.started = true;
        InstanceStats.AutoJoinCancel = false;
        return;
    }
    if(!InstanceStats.started) return;
    switch (message) {
        case "                                   DEFEAT":
            InstanceStats.started = false;
            InstanceStats.end = true;
            if(settings.AutoRequeueKuudra == 1.0 || settings.AutoRequeueKuudra == 3.0) InstanceRequeue(settings.AutoRequeueKuudraText,2);
            break;
        case "                               KUUDRA DOWN!":
            InstanceStats.started = false;
            InstanceStats.end = true;
            if(settings.AutoRequeueKuudra == 2.0 || settings.AutoRequeueKuudra == 3.0) InstanceRequeue(settings.AutoRequeueKuudraText,settings.AutoRequeueKuudraDelay);
            break;
        case "                             > EXTRA STATS <":
            InstanceStats.started = false;
            InstanceStats.end = true;
            if(settings.AutoRequeueDungeon == 1.0 || settings.AutoRequeueDungeon == 3.0) InstanceRequeue(settings.AutoRequeueDungeonText,settings.AutoRequeueDungeonDelay);    
            break;
        default:
            if(message.startsWith("     ") && message.includes("   ☠ Defeated ") && message.includes(" in ")) {
                InstanceStats.started = false;
                InstanceStats.end = true;
                DungeonComp();
                if(settings.AutoRequeueDungeon == 2.0 || settings.AutoRequeueDungeon == 3.0) InstanceRequeue(settings.AutoRequeueDungeonText,settings.AutoRequeueDungeonDelay);
            }
            break;
    }
}).setCriteria("${message}")

register("chat", (party,rank,player,sign,message)=>{
    if(!(location.inDungeon || location.inKuudra) || InstanceStats.AutoJoinCancel) return;
    try {
        let CancelText = (settings.AutoRequeueText.includes('|') ? settings.AutoRequeueText.toLowerCase().split('|') : [settings.AutoRequeueText]);
        if(CancelText.indexOf(message.toLowerCase()) != -1) InstanceStats.CancelAutoJoin(stripRank(player) == Player.getName());
    } catch (error) {}
}).setCriteria(/(组队|組隊|Party) > (\[[\w+\+-]+] )?([0-9a-zA-Z_]+)( [♲Ⓑ☀⚒ቾ]+)?: (.+)/i)

register("command",()=>{
    if(location.inDungeon || location.inKuudra) InstanceStats.CancelAutoJoin(true);
}).setName("nr")


export function dailycheck(player) {
    getSBProfile(player).then(p=>{
        const days = p.dungeons.daily_runs.current_day_stamp
        const ms = days * 3600 * 24 * 1000;
        const date = new Date(ms);
        const day = date.getFullYear() + ":" + (date.getMonth() + 1) + ":" + date.getDate();
        ChatLib.chat("§6§l[BZA] §b" + p.name + " §e最近的地牢记录 \n§a日期 §7: §b" + day 
        + "     §a场数 §7: §b" + p.dungeons.daily_runs.completed_runs_count);
    })
}